Page({
  data: {
    // 表单数据
    form: {
      name: '',
      idCard: '',
      age: '',
      phone: '',
      address: '',
      familySize: '',
      monthlyIncome: '',
      incomeSource: '',
      subsidyType: '',
      bankName: '',
      bankAccount: '',
      reason: '',
      idCardImage: '',
      householdImage: '',
      pensionImage: '',
      otherImage: ''
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

    // 收入来源选项
    incomeSources: ['务农收入', '打工收入', '经商收入', '退休金', '低保补助', '其他收入', '无固定收入'],
    incomeSourceIndex: -1,

    // 补贴类型选项
    subsidyTypes: ['基础养老补贴', '高龄津贴', '困难老人补助', '空巢老人关爱补贴'],
    subsidyTypeIndex: -1,

    // 申请声明同意状态
    agreed: false,

    // 表单验证状态
    canSubmit: false,

    // 字段错误与展示控制
    errors: {},
    showErrors: false
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('服务事项加载中...')
    console.log('养老补贴申请页面加载', options);
    
    // 页面加载完成，隐藏加载状态
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)
  },

  // 输入框变化处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;

    this.setData({
      [`form.${field}`]: value
    }, () => {
      this.validateForm();
    });
  },

  // 收入来源选择器变化处理
  onIncomeSourceChange(e) {
    const { value } = e.detail;
    const incomeSource = this.data.incomeSources[value];

    this.setData({
      incomeSourceIndex: value,
      'form.incomeSource': incomeSource
    }, () => {
      this.validateForm();
    });
  },

  // 补贴类型选择器变化处理
  onSubsidyTypeChange(e) {
    const { value } = e.detail;
    const subsidyType = this.data.subsidyTypes[value];

    this.setData({
      subsidyTypeIndex: value,
      'form.subsidyType': subsidyType
    }, () => {
      this.validateForm();
    });
  },

  // 上传身份证照片
  onUploadIdCard() {
    this.chooseAndUploadImage('idCardImage');
  },

  // 上传户口簿照片
  onUploadHousehold() {
    this.chooseAndUploadImage('householdImage');
  },

  // 上传养老金领取证明
  onUploadPension() {
    this.chooseAndUploadImage('pensionImage');
  },

  // 上传其他证明
  onUploadOther() {
    this.chooseAndUploadImage('otherImage');
  },

  // 通用图片选择和上传方法
  chooseAndUploadImage(fieldName) {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;

        // 上传到服务器
        setTimeout(() => {
          this.setData({ [`form.${fieldName}`]: tempFilePath }, () => {
            this.validateForm();
          });
          wx.showToast({ title: '上传成功', icon: 'success' });
        }, 1000);
      },
      fail: (err) => {
        console.error('选择图片失败', err);
        wx.showToast({ title: '图片选择失败', icon: 'none' });
      }
    });
  },

  // 申请声明变化处理
  onDeclarationChange(e) {
    const agreed = e.detail.value.includes('agree');
    this.setData({ agreed }, () => { this.validateForm(); });
  },

  // 表单验证
  validateForm() {
    const { form, agreed, showErrors } = this.data;

    const requiredFields = ['name', 'idCard', 'age', 'phone', 'address', 'familySize', 'monthlyIncome', 'incomeSource', 'subsidyType', 'reason'];
    const isBasicInfoValid = requiredFields.every(field => form[field] && form[field].toString().trim());

    const requiredImages = ['idCardImage', 'householdImage'];
    const isImagesValid = requiredImages.every(field => form[field]);

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    const isIdCardValid = idCardRegex.test(form.idCard);

    const phoneRegex = /^1[3-9]\d{9}$/;
    const isPhoneValid = phoneRegex.test(form.phone);

    const canSubmit = isBasicInfoValid && isImagesValid && isIdCardValid && isPhoneValid && agreed;

    const errors = {};
    if (showErrors) {
      const fieldNames = {
        name: '姓名',
        idCard: '身份证号',
        age: '年龄',
        phone: '联系电话',
        address: '家庭住址',
        familySize: '家庭人口数',
        monthlyIncome: '家庭月收入',
        incomeSource: '主要收入来源',
        subsidyType: '补贴类型',
        reason: '申请说明'
      };

      requiredFields.forEach((field) => {
        if (!form[field] || !form[field].toString().trim()) {
          errors[field] = `请填写${fieldNames[field]}`;
        }
      });

      if (!form.idCardImage) errors.idCardImage = '请上传身份证照片';
      if (!form.householdImage) errors.householdImage = '请上传户口簿照片';

      if (form.idCard && !isIdCardValid) errors.idCard = '身份证号格式不正确';
      if (form.phone && !isPhoneValid) errors.phone = '手机号格式不正确';
      if (!agreed) errors.agreed = '请勾选申请声明';
    }

    this.setData({ canSubmit, errors });
  },

  // 提交申请
  onSubmit() {
    this.setData({ showErrors: true }, () => {
      this.validateForm();
      if (!this.data.canSubmit) {
        wx.showToast({ title: '请完善申请信息', icon: 'none' });
        return;
      }

      setTimeout(() => {
        wx.showModal({
          title: '申请提交成功',
          content: '您的养老补贴申请已提交，我们将在3-5个工作日内完成审核，请耐心等待。',
          showCancel: false,
          confirmText: '确定',
          success: () => {
            wx.navigateBack({ delta: 1 });
          }
        });
      }, 2000);
    });
  },

  onShareAppMessage() {
    return {
      title: '养老补贴申请',
      path: '/pages/service/civil-affairs/pension-subsidy/index'
    };
  }
});


